package com.xiaoxin.smartbi.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.io.Files;
import com.xiaoxin.smartbi.annotation.AuthCheck;
import com.xiaoxin.smartbi.bizmq.BiMessageProducer;
import com.xiaoxin.smartbi.common.BaseResponse;
import com.xiaoxin.smartbi.common.DeleteRequest;
import com.xiaoxin.smartbi.common.ErrorCode;
import com.xiaoxin.smartbi.common.ResultUtils;
import com.xiaoxin.smartbi.constant.FileConstant;
import com.xiaoxin.smartbi.constant.UserConstant;
import com.xiaoxin.smartbi.exception.BusinessException;
import com.xiaoxin.smartbi.exception.ThrowUtils;
import com.xiaoxin.smartbi.manager.AiManager;
import com.xiaoxin.smartbi.manager.RateLimiterManager;
import com.xiaoxin.smartbi.model.dto.chart.*;
import com.xiaoxin.smartbi.model.dto.file.UploadFileRequest;
import com.xiaoxin.smartbi.model.dto.post.PostQueryRequest;
import com.xiaoxin.smartbi.model.entity.Chart;
import com.xiaoxin.smartbi.model.entity.Post;
import com.xiaoxin.smartbi.model.entity.User;
import com.xiaoxin.smartbi.model.enums.FileUploadBizEnum;
import com.xiaoxin.smartbi.model.vo.BiResponse;
import com.xiaoxin.smartbi.model.vo.PostVO;
import com.xiaoxin.smartbi.service.ChartService;
import com.xiaoxin.smartbi.service.UserService;
import com.xiaoxin.smartbi.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;
    // region 增删改查

    @Resource
    private RateLimiterManager rateLimiterManager;
    
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiMessageProducer biMessageProducer;
    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 调用ai生成图表（同步）
     * @param multipartFile excel文件
     * @param genChartRequest 生成图表请求
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                             GenChartRequest genChartRequest, HttpServletRequest request) {
        String goal = genChartRequest.getGoal();
        String name = genChartRequest.getName();
        String chartType = genChartRequest.getChartType();
        //校验用户请求
        if(StringUtils.isBlank(goal)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"分析目标为空");
        }
        if(StringUtils.isNotBlank(name)&&name.length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表名称过长");
        }
        if(StringUtils.isBlank(chartType)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表类型为空");
        }
        //校验用户传入文件的合法性
        //文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        List<String> suffixList= Arrays.asList("xlsx","xls");
        if(!suffixList.contains(suffix)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件后缀不合法");
        }
        //文件大小
        long size = multipartFile.getSize();
        long ONE_MB=1024*1024;
        if(size>ONE_MB){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件过大");
        }
        //限流器限流，每秒只允许调用ai两次
        rateLimiterManager.rateLimiter(String.valueOf(userService.getLoginUser(request).getId()));
        String excelToCsv = ExcelUtils.excelToCsv(multipartFile);
        StringBuilder input=new StringBuilder();
        input.append("分析需求：\n"+goal+"，请使用"+chartType).append("\n");
        input.append("原始数据：\n"+excelToCsv);
        String result = aiManager.result(input.toString());
        String[] resultArray=result.split("【【【【");
        BiResponse biResponse=new BiResponse();
        biResponse.setGenChart(resultArray[1]);
        biResponse.setGenResult(resultArray[2]);
        Chart chart=new Chart();
        chart.setGoal(goal);
        chart.setName(name);
        chart.setChartType(chartType);
        chart.setChartData(excelToCsv);
        chart.setGenChart(resultArray[1]);
        chart.setGenResult(resultArray[2]);
        chart.setUserId(userService.getLoginUser(request).getId());
        boolean save = chartService.save(chart);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图标信息保存失败");
        }
        return ResultUtils.success(biResponse);
    }

    /**
     * 调用ai生成图表（异步）
     * @param multipartFile excel文件
     * @param genChartRequest 生成图表请求
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartRequest genChartRequest, HttpServletRequest request) {
        String goal = genChartRequest.getGoal();
        String name = genChartRequest.getName();
        String chartType = genChartRequest.getChartType();
        //校验用户请求
        if(StringUtils.isBlank(goal)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"分析目标为空");
        }
        if(StringUtils.isNotBlank(name)&&name.length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表名称过长");
        }
        if(StringUtils.isBlank(chartType)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表类型为空");
        }
        //校验用户传入文件的合法性
        //文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        List<String> suffixList= Arrays.asList("xlsx","xls");
        if(!suffixList.contains(suffix)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件后缀不合法");
        }
        //文件大小
        long size = multipartFile.getSize();
        long ONE_MB=1024*1024;
        if(size>ONE_MB){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件过大");
        }
        //限流器限流，每秒只允许调用ai两次
        rateLimiterManager.rateLimiter(String.valueOf(userService.getLoginUser(request).getId()));
        String excelToCsv = ExcelUtils.excelToCsv(multipartFile);
        StringBuilder input=new StringBuilder();
        input.append("分析需求：\n"+goal+"，请使用"+chartType).append("\n");
        input.append("原始数据：\n"+excelToCsv);

        //状态1，调用ai前
        Chart chart1=new Chart();
        chart1.setGoal(goal);
        chart1.setName(name);
        chart1.setChartType(chartType);
        chart1.setChartData(excelToCsv);
        chart1.setUserId(userService.getLoginUser(request).getId());
        chart1.setUserId(userService.getLoginUser(request).getId());
        boolean save = chartService.save(chart1);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图标信息保存失败");
        }
        CompletableFuture.runAsync(()->{
            String result = aiManager.result(input.toString());
            //状态2，ai生成中
            Chart chart2=new Chart();
            chart2.setId(chart1.getId());
            chart2.setStatus("running");
            String[] resultArray= result.split("【【【【");
            chart2.setGenChart(resultArray[1]);
            chart2.setGenResult(resultArray[2]);
            boolean update = chartService.updateById(chart2);
            if(!update){
                //状态3，ai生成失败
                Chart chart3=new Chart();
                chart3.setId(chart1.getId());
                chart3.setStatus("filed");
                boolean update2 = chartService.updateById(chart3);
                if(!update2){
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图标信息保存失败");
                }
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"ai生成图表失败");
            }
            Chart chart4=new Chart();
            chart4.setId(chart1.getId());
            chart4.setStatus("succeed");
            boolean update4 = chartService.updateById(chart4);
            if(!update4){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图标信息保存失败");
            }
        },threadPoolExecutor);
        BiResponse biResponse=new BiResponse();
        return ResultUtils.success(biResponse);
    }

    /**
     * 调用ai生成图表（异步）
     * @param multipartFile excel文件
     * @param genChartRequest 生成图表请求
     * @param request
     * @return
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncBymq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartRequest genChartRequest, HttpServletRequest request) {
        String goal = genChartRequest.getGoal();
        String name = genChartRequest.getName();
        String chartType = genChartRequest.getChartType();
        //校验用户请求
        if(StringUtils.isBlank(goal)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"分析目标为空");
        }
        if(StringUtils.isNotBlank(name)&&name.length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表名称过长");
        }
        if(StringUtils.isBlank(chartType)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表类型为空");
        }
        //校验用户传入文件的合法性
        //文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        List<String> suffixList= Arrays.asList("xlsx","xls");
        if(!suffixList.contains(suffix)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件后缀不合法");
        }
        //文件大小
        long size = multipartFile.getSize();
        long ONE_MB=1024*1024;
        if(size>ONE_MB){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件过大");
        }
        //限流器限流，每秒只允许调用ai两次
        rateLimiterManager.rateLimiter(String.valueOf(userService.getLoginUser(request).getId()));
        String excelToCsv = ExcelUtils.excelToCsv(multipartFile);
        StringBuilder input=new StringBuilder();
        input.append("分析需求：\n"+goal+"，请使用"+chartType).append("\n");
        input.append("原始数据：\n"+excelToCsv);

        //状态1，调用ai前
        Chart chart1=new Chart();
        chart1.setGoal(goal);
        chart1.setName(name);
        chart1.setChartType(chartType);
        chart1.setChartData(excelToCsv);
        chart1.setUserId(userService.getLoginUser(request).getId());
        chart1.setUserId(userService.getLoginUser(request).getId());
        boolean save = chartService.save(chart1);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图标信息保存失败");
        }
        biMessageProducer.sendMessage(String.valueOf(chart1.getId()));
        BiResponse biResponse=new BiResponse();
        biResponse.setId(chart1.getId());
        return ResultUtils.success(biResponse);
    }
}
















